package NG::Sys::Loop::DBDaemon;
use strict;
use warnings;
use utf8;

use EV;
use base 'NG::Sys::Loop::Daemon';


sub on_prepare_loop {
	my($app) = @_;
	$app->{data} = {
		dbh => $app->dbh,
		sql => $app->{sql},
	};
	$app->{data}{sth} = $app->{data}{dbh}->prepare($app->{data}{sql});
}
sub on_enter_loop {
	my($app) = @_;
	$app->{data}{param} = [];
	die "need override 'on_enter_loop'";
	return  1; # yes, enter to loop
}
sub on_before_process {
	my($app) = @_;
	$app->{data}{sth}->execute(@{$app->{data}{param}});
	$app->{data}{list} = $app->{data}{sth}->fetchall_arrayref({});
	return scalar(@{$app->{data}{list}});
}
sub on_process {
	my($app) = @_;
	die "need overrride 'on_process'";
	for my $row(@{$app->{data}{list}}){
	}
	return 1; # yes, do after_process
}
sub on_after_process {
	my($app) = @_;
	$app->{data}{list} = undef;
}
sub on_delay_loop {
	my ($self) = @_;
	my $delay = $self->arg->{delay} || $self->{delay};
	if($delay && $delay > 0){
		my $elapsed = $self->{loop}{done} - $self->{loop}{begin};
		$delay -= $elapsed;
		if($delay > 0){
			sleep int($delay);
		}
	}
}

1;
